import { Component, OnInit, AfterViewChecked, ViewChild, Input } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ConfirmationService, SelectItem } from 'primeng/primeng';
import { MdlSnackbarService } from '@angular-mdl/core';
import { Location } from '@angular/common';
import { HumanService } from './service/human.service';
import { flyIn } from '../../common/animation/common.animation';
@Component({
  selector: 'human-detail',
  templateUrl: './human-detail.component.html',
  styleUrls: ['./human-detail.component.scss'],
  animations: [flyIn]
})
export class HumanDetailComponent implements OnInit {
  humanTypes: SelectItem[] = [{ 'label': '执法人员', 'value': 0 }];
  humanItem: any = {};
  humanForm: FormGroup;

  @Input()
  set human(human: any) {
    if (!human) return;
    this.humanItem = human;
    this.buildForm()
  }

  get human(): any { return this.humanItem; }

  constructor(
    private humanService: HumanService,
    private fb: FormBuilder,
    private location: Location,
    private mdlSnackbarService: MdlSnackbarService,
    private confirmationService: ConfirmationService) { }

  ngOnInit(): void {
    this.buildForm();
  }
  /**保存或更新人员信息 */
  saveUpdate() {
    this.humanService.saveUpdateHuman(this.humanForm.value)
      .subscribe(data => {
        this.humanService.announceMission(data);
        this.mdlSnackbarService.showToast('数据保存成功！');
      });
  }

  /** 删除人员信息 */
  delete() {
    this.confirmationService.confirm({
      header: '确认',
      message: '您确定要删除该条记录吗？',
      accept: () => {
        this.humanService.delete(this.humanItem.humanId).subscribe(data => {
          this.humanService.announceMission(this.humanItem);
          this.mdlSnackbarService.showToast('数据删除成功！');
        });
      }
    });
  }

  buildForm(): void {
    this.humanForm = this.fb.group({
      'humanId': [this.humanItem.humanId],
      'unitId': [this.humanItem.unitId],
      'unitCode': [this.humanItem.unitCode],
      'unitName': [this.humanItem.unitName],
      'humanName': [this.humanItem.humanName, Validators.required],
      'userName': [this.humanItem.userName, [
        Validators.required
      ]
      ],
      'telephone': [this.humanItem.telephone],
      'createUser': [this.humanItem.createUser],
      'createTime': [this.humanItem.createTime],
      'loginFlag': [this.humanItem.loginFlag],
      'humanDesc': [this.humanItem.humanDesc]
    });
  }

  /**返回操作 */
  goBack($event: any) {
    if (this.humanForm.dirty) {
      this.confirmationService.confirm({
        header: '确认',
        message: '您确定要放弃保存修改的记录吗？',
        accept: () => { this.location.back()}
      });
    } else {
      this.location.back();
    }
  }

}
